#!/usr/bin/python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import sys,getopt

argHash = {}
#textType = {'text':MIMEText(text,'plain') , 'html':MIMEText(html, 'html')}
textType = {'text':'plain' , 'html':'html'}

def usage():
        print """\

usage of SendMail.py:\n
        -h, --help:
            print this page.
        -m, --mail-type:
            mail type: html ,txt
        -s, --subject:
            the subject of the mail
        -i, --source-email:
            source email address
        -u, --target-email:
            target mail address
        -f, --mail-file:
            the file with mail body msg
        \n
        example:
                SendMail -m text -s 'this is a test' -i orinbai@sina.com -u orinbai@gmail.com -f /opt/path/sample.eml
                or:
                SendMail --mail-type=text --subject='this is a test' --source-email=orinbai@sina.com --target-email=orinbai@gmail.com --mail-file=/opt/path/sample.eml

        """

def getArgs(Args):
        mailist = []
        try:
                my_args = getopt.getopt(Args,'hm:s:i:u:f:', ['help', 'mail-type=', 'subject=', 'source-email=', 'target-email=', 'mail-file='])
        except getopt.GetoptError, err:
                print '-----'
                print str(err)
                usage()
                sys.exit(2)
        tmpHash = {}
        for a in filter(lambda x: x, my_args[0]):
                ### Print Help Msg ###
                if '-h' in a or '--help' in a:
                        usage()
                        exit(2)
                elif '-s' in a or '--subject' in a:
                        tmpHash['subject'] = a[1]
                        continue
                elif '-i' in a or '--source-email' in a:
                        tmpHash['me'] = a[1]
                        continue
                elif '-m' in a or '--mail-type' in a:
                        tmpHash['mailtype'] = a[1]
                        continue
                elif '-u' in a or '--target-email' in a:
                        if ',' in a[1]:
                                mailist = a[1].split(',')
                        else:
                                mailist.append(a[1])
                        tmpHash['you'] = mailist
                        #tmpHash['you'] = a[1]
                        continue
                elif '-f' in a or '--mail-file' in a:
                        tmpHash['file'] = a[1]
                        continue
        if len(tmpHash) < 5:
                print 'I need every arg except -h, --help.'
                print 'Please read help.'
                usage()
                sys.exit(2)

        #return filter(lambda x: x, 
        return tmpHash

if len(sys.argv) > 1:
        argHash = getArgs(sys.argv[1:])
else:
        usage()
        sys.exit(2)


# me == my email address
# you == recipient's email address
me = argHash['me']
you = argHash['you']

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
#msg['Subject'] = argHash['subject'].decode('gb2312').encode('gb2312')
msg['Subject'] = argHash['subject']
msg['From'] = me
msg['To'] = ';'.join(you)

# Create the body of the message (a plain-text and an HTML version).
#text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
#html = """\
#<html>
#  <head></head>
#  <body>
#    <p>Hi!<br>
#       How are you?<br>
#       Here is the <a href="http://www.python.org">link</a> you wanted.
#    </p>
#  </body>
#</html>
#"""

f = open(argHash['file'])
mailContent= f.read().decode('gb2312').encode('utf8')
f.close()

# Record the MIME types of both parts - text/plain and text/html.
#part1 = MIMEText(text, 'plain')
#part2 = MIMEText(html, 'html')
part = MIMEText(mailContent, textType[argHash['mailtype']],'utf8')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
#msg.attach(part1)
#msg.attach(part2)
msg.attach(part)

# Send the message via local SMTP server.
#s = smtplib.SMTP('staff.sina.com.cn')
s = smtplib.SMTP('smtp.sina.com')
s.set_debuglevel(2)
s.login('check_status', '123456')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
